<template>
	<view class="content">
		<!-- 轮播图 -->
		<view v-if="loading" class="loading">加载中...</view>
		<swiper :autoplay="true" :interval="3000" @change="onSwiperChange" class="header-swiper">
			<swiper-item v-for="(item, index) in imageList" :key="index">
				<image :src="item.image" mode="aspectFill" class="swiper-image" />
			</swiper-item>
		</swiper>

		<!-- 指示器 -->
		<view class="indicator">
			<view class="indicator-line" v-for="(item, index) in imageList" :key="index"
				:class="['indicator-dot', {active: current == index}]"></view>
		</view>

		<!-- 搜索 -->
		<view class="search_name" @click="toSearchView()">
			<image src="../../static/search.png" mode="widthFix"
				style="width: 30rpx;height: 30rpx;margin: 35rpx 40rpx;float: left;position: absolute;"></image>
			<input type="text" class="search_input" placeholder="请输入品牌名称" />
			<button class="search_btn">搜索</button>
		</view>

		<!-- 券类别 -->
		<view class="ticket">
			<view class="ticket_left">
				<ul class="ticket_list">
					<li v-for="(category, index) in categories" :key="category.id"
						@click="handleSidebarClick(category.id, index)" :class="{ active: currentCategory === index }">
						{{ category.name }}
					</li>
				</ul>
			</view>

			<!-- 所有品牌展示 -->
			<view class="ticket_right">
				<view class="brand-grid">

					<view v-for="(brand, i) in brands" :key="i">
						<view v-if="i < 7 || isShow" @click="handleBrandClick(brand.id,i)" class="brand-item">
							<image :src="brand.image" alt="品牌图" class="brand-image" />
							<text :class="[brandIndex == i ? 'blue' : '','brand_text']">{{ brand.name }}</text>
						</view>
					</view>
					<view>
						<view class="brand-item" @click="viewAll" v-if="total >= 7 && !isShow ">
							<image src="../../static/icon/icon_01.png" alt="全部" class="top" />
							<text class="brand_text">展开</text>
						</view>
					</view>
					<view>
						<view class="brand-item" @click="closeAll" v-if="total >= 7 && isShow ">
							<image src="../../static/icon/icon_01.png" alt="收起" class=" bottom" />
							<text class="brand_text">收起</text>
						</view>
					</view>
				</view>


				<!-- 卡券类型展示 -->
				<view v-show="cardTypeList.length > 0" style="height:30vh">
					<view class="Card_type" v-for="cardType in cardTypeList" :key="cardType.id"
						@click="goDetail(cardType)">
						<image :src="cardType.image" mode="aspectFit" class="Card_type_icon"></image>
						<view class="card_details">
							<text class="card_tp_title">{{ cardType.name }}</text>
							<view class="card_tp_rmb">
								回收价: <text class="card_rmb_num">￥{{ cardType.buyPrice }}</text>
								补贴: <text class="card_rmb_num">￥{{ cardType.subsidy }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getBanner,
		getMenulist,
		getBrandlist,
		getCardBrandList,
		getMemberInfo,
		memberLogin
	} from '@/api.js'
	export default {
		data() {
			return {
				loading: true, // 加载状态
				imageList: [], // 轮播图数据
				current: 0, // 当前轮播图索引
				categories: [], // 券类别数据
				currentCategory: 0, // 当前选中的券类别索引
				brands: [], // 品牌数据，初始化为空数组
				cardTypeList: [], // 存储卡券类型数据
				currentBrandId: null, // 当前选中的品牌 ID
				isShow: false, //是否显示全部商家
				total: 0,
				brandIndex: 0, //选中品牌的索引
			}
		},
		onLoad(options) {
			let url = window.location.href
			let result = url.replace(new RegExp('#', "g"), "");
			let myUrl = new URL(result)
			let inviteCode = myUrl.searchParams.get('inviteCode')
			if (inviteCode) {
				let code = inviteCode.slice(0, 6)
				uni.setStorageSync('inviteCode', code);
			}
			this.init(); // 页面加载时调用初始化方法
			this.getList()
		},
		methods: {
			// 点击显示更多
			viewAll() {
				this.isShow = true
				console.log('展示更多');
			},
			// 点击关闭更多
			closeAll() {
				this.isShow = false
			},
			//跳转搜索页面
			toSearchView() {
				console.log(1111);
				//点击跳转到搜索页面
				uni.navigateTo({
					url: '/pages/search/search'
				})
			},
			onSwiperChange(e) {
				this.current = e.detail.current;
			},
			toggleCategory(index) {
				this.currentCategory = index;
			},
			async GetUser() {
				let res = await getMemberInfo({
					// token: uni.getStorageSync('token')
				})
				console.log('用户信息', res);
				this.userInfo = res.result
				uni.setStorage({
					key: 'userInfo',
					data: JSON.stringify(res.result),
					success: function() {}
				});
			},
			async init() {
				this.getBannerList();
				let that = this
				if (uni.getStorageSync('token')) {
					this.GetUser()
					return
				}
				let url = window.location.href
				let result = url.replace(new RegExp('#', "g"), "");
				let myUrl = new URL(result)
				let code = myUrl.searchParams.get('code')
				console.log('code', code)
				if (code) {
					// 调用登录方法
					let res = await memberLogin({
						code
					})
					console.log('登录返回结果', res);
					if (res.code === 200 && res.success) {
						const token = res.result.token;
						uni.setStorage({
							key: 'token',
							data: token,
							success: function() {
								console.log('token');
								that.GetUser()
							}
						});
					} else {
						console.error('登录失败，错误信息:', res.message);
					}
				} else {}
			},
			async getBannerList() {
				console.log('获取轮播图');
				let res = await getBanner({})
				if (res.code == 200) {
					this.loading = false;
					this.imageList = res.result
				} else {
					console.error('获取轮播图数据失败:', res.data.message);
				}
			},
			// 获取卡券列表和品牌列表
			async getList() {
				try {
					// 获取卡券列表
					const response = await getMenulist();
					const cardList = response.result.records;
					const cardData = cardList.map(card => ({
						name: card.name,
						id: card.id
					}));

					// 默认选中第一个卡券类别
					this.categories = cardData; // 设置类别数据
					this.currentCategory = 0; // 设置默认选中的类别

					// 获取品牌列表
					const res = await getBrandlist({
						oneId: cardData[0].id
					});
					const brandList = res.result.records;
					const brandData = brandList.map(brand => ({
						name: brand.name,
						image: brand.image,
						id: brand.id
					}));

					// 更新品牌数据
					this.brands = brandData;
					// console.log('品牌list', this.brands);
				} catch (error) {
					console.error('请求列表数据失败:', error);
				} finally {
					this.loading = false;
				}
			},

			// 左侧侧栏点击事件
			async handleSidebarClick(id, index) {
				if (this.currentCategory == index) {
					return
				}
				try {
					this.cardTypeList = []
					// 更新当前选中的分类索引
					this.currentCategory = index;
					// 调用获取品牌列表接口，传递对应的id
					const res = await getBrandlist({
						oneId: id
					});
					if (res.code === 200) {
						const brandList = res.result.records;
						const brandData = brandList.map(brand => ({
							name: brand.name,
							image: brand.image,
							id: brand.id
						}));
						// 更新品牌数据
						this.brands = brandData;
						this.total = res.result.total
						if (res.result.total < 7) {
							this.isShow = false
						}
					} else {
						console.error('获取品牌列表失败:', res.message);
					}
				} catch (error) {
					console.error('请求品牌列表失败:', error);
				} finally {
					this.loading = false; // 结束加载
				}
			},

			// 处理品牌点击事件
			async handleBrandClick(brandId, i) {
				this.brandIndex = i
				try {
					// 清空 cardTypeList
					this.cardTypeList = [];

					// 获取当前选中的分类 ID
					const currentCategoryId = this.categories[this.currentCategory].id;

					// 调用获取卡券类型列表接口
					const res = await getCardBrandList({
						oneId: currentCategoryId,
						brandId: brandId,
						pageSize: 9999,
						pageNo: 1,
						name: ''
					});

					if (res.code == 200 && res.result.records.length > 0) {
						// 更新 cardTypeList 数据
						this.cardTypeList = res.result.records;
						console.log('卡券类型列表:', this.cardTypeList);
					} else {
						console.log('该品牌没有卡券类型');
						this.cardTypeList = []; // 确保卡券列表为空
					}
				} catch (error) {
					console.error('请求卡券类型列表失败:', error);
				}

			},
			// 跳转卡券详情
			goDetail(item) {

				console.log('item', item);

				if (uni.getStorageSync('token')) {
					let obj = {
						lifespan: item.lifespan,
						name: item.name,
						buyPrice: item.buyPrice,
						image: item.image,
						id: item.id,
						subsidy: item.subsidy,
						uploadType: item.uploadType
					}
					console.log('userInfo', JSON.parse(uni.getStorageSync('userInfo')));
					// && JSON.parse(uni.getStorageSync('userInfo')).phone
					if (JSON.parse(uni.getStorageSync('userInfo')).idCard) {
						uni.navigateTo({
							url: `/pages/uploadCoupons/uploadCoupons?params=${JSON.stringify(obj)}`
						})
					} else {
						uni.showModal({
							title: '提示',
							content: '请先实名认证',
							confirmText: '去认证',
							success: function(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/seting/seting'
									})
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					}

				} else {
					uni.showToast({
						icon: 'none',
						title: '请先登录',
						duration: 2000,
						complete() {
							setTimeout(() => {
								uni.switchTab({
									url: '/pages/user/user'
								})
							}, 2000)
						},
					});
				}
			}
		},
	}
</script>

<style>
	* {
		padding: 0;
		margin: 0;
		box-sizing: border-box;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.header-swiper {
		width: 100%;
		height: 270rpx;
		position: relative;
	}

	.header-swiper image {
		width: 100%;
		height: 100%;
	}

	.indicator {
		position: absolute;
		top: 250rpx;
		left: 50%;
		transform: translateX(-50%);
		display: flex;
		gap: 10px;
	}

	.indicator-dot {
		width: 20px;
		height: 4px;
		background-color: #fff;
		border-radius: 2px;
	}

	.indicator-dot.active {
		background-color: #3380ff;
		opacity: 1;
	}

	.header-swiper {
		width: 100%;
		height: 270rpx;
		position: relative;
	}

	.header-swiper image {
		width: 100%;
		height: 100%;
	}

	.search_name {
		width: 100%;
		height: 80rpx;
		display: flex;
		justify-content: space-between;
		background-color: #ffffff;
	}

	.search_input {
		margin: 20rpx;
		padding: 10rpx 60rpx;
		width: 75%;
		height: 60rpx;
		border: 1px solid #eeeeee;
		border-radius: 50rpx;
		font-size: 24rpx;
		background-color: #eaeaea;
		color: #c0c4cc;
	}

	.search_btn {
		float: left;
		margin-top: 20rpx;
		margin-right: 20rpx;
		border-radius: 30rpx;
		width: 17%;
		height: 60rpx;
		font-size: 24rpx;
		background-color: #3c9cff;
		color: #e0f0ff;
	}

	.ticket {
		display: flex;
		border-top: 2px solid #eeee;
		margin-top: 10rpx;
		width: 100%;
		height: auto;
	}

	.ticket_left {
		width: 20%;
		height: auto;
		overflow: scroll;
		background-color: #ffffff;
	}

	.ticket_list {
		padding: 0;
		height: 100%;
	}

	.ticket_list li {
		padding: 35rpx 25rpx;
		font-size: 24rpx;
		text-align: center;
		background-color: #f6f6f6;
		color: #444444;
		cursor: pointer;
	}

	.ticket_left li.active {
		color: #3380ff;
		background-color: #ffffff;
	}

	.ticket_right {
		width: 80%;
		height: 70vh;
		background-color: #fafafa;
	}

	.brand-grid {
		width: 80vw;
		display: flex;
		flex-wrap: wrap;
		align-items: center;
	}

	.brand-item {
		width: 20vw;
		display: flex;
		align-items: center;
		flex-direction: column;
		margin-top: 8px;
	}

	.brand-item .top {
		transform: rotate(90deg);
		width: 40rpx;
		height: 40rpx;
		margin: 30rpx;
	}

	.brand-item .bottom {
		transform: rotate(-90deg);
		width: 40rpx;
		height: 40rpx;
		margin: 30rpx;
	}


	.brand-image {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50rpx;
	}

	.brand_text {
		width: 100rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		margin-top: 5px;
		font-weight: 400;
		font-size: 10px;
		color: #303133;
		height: 34px;
		overflow: hidden;
		text-overflow: ellipsis;
		text-align: center;
		box-sizing: border-box;
		padding: 0 2px;
	}

	.Card_type {
		margin: 10rpx 0;
		padding: 20rpx;
		width: 100%;
		height: auto;
		background-color: #ffffff;
		display: flex;
		align-items: center;
		border-bottom: 1px solid #eeeeee;
	}

	.Card_type_icon {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		margin-right: 20rpx;
	}

	.card_details {
		flex: 1;
		font-size: 26rpx;
	}

	.card_tp_title {
		font-size: 30rpx;
		font-weight: bold;
	}

	.card_tp_rmb {
		margin-top: 10rpx;
	}

	.card_rmb_num {
		font-size: 30rpx;
		font-weight: bold;
		color: #ff0604;
	}

	.dis_back {
		display: block;
	}

	.dis_none {
		display: none;
	}

	.back {
		width: 80vw;
		height: 200rpx;
		background: rgba(0, 0, 0, 0.2);
		position: relative;
	}

	.close_all {
		position: absolute;
		top: 16rpx;
		left: 50%;
		margin-left: -12rpx;
		width: 48rpx;
		height: 48rpx;
	}

	.blue {
		color: #218ad5;
	}
</style>